<template>
  <div>
    <el-form ref="ruleFormRef" label-width="150px" class="ruleForm" :model="form" :rules="rules">
      <div class="page-container">

        <el-form-item label="角色名称：" prop="name">
          <el-col :span="10">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-col>
        </el-form-item>
        <el-form-item label="角色描述：" prop="remark">
          <el-col :span="10">
            <el-input v-model="form.remark" placeholder="请输入角色描述" />
          </el-col>
        </el-form-item>
        <el-form-item label="角色权限：" required>
          <el-col :span="20">
            <div class="role-right" v-for="group in list" :key="group.name">
              <div class="right-title">
                <el-checkbox :indeterminate="group.isIndeterminate" @change="handleParentChange(group)" v-model="group.check">{{ group.name }}</el-checkbox>
              </div>
              <template v-if="group.children">
                <div class="ml40" v-for="onerole in group.children" :key="onerole.name">
                  <el-checkbox :indeterminate="onerole.isIndeterminate" @change="handleItemChange([onerole,group])" v-model="onerole.check">{{ onerole.name }}</el-checkbox>
                  <template v-if="onerole.children">
                    <div class="ml40" v-for="towrole in onerole.children" :key="towrole.name">
                      <el-checkbox :indeterminate="towrole.isIndeterminate" @change="handleItemChange([towrole,onerole,group])" v-model="towrole.check">{{ towrole.name }}</el-checkbox>
                      <!--三级-->
                      <ul>
                        <li v-for="threeole in towrole.permissions" :key="threeole.id">
                          <el-checkbox @change="handleItemChange([threeole,towrole,onerole,group])" v-model="threeole.check">{{ threeole.name }}</el-checkbox>
                        </li>
                      </ul>
                    </div>
                  </template>
                  <template v-else>
                    <!--二级-->
                    <ul>
                      <li v-for="towrole in onerole.permissions" :key="towrole.id">
                        <el-checkbox @change="handleItemChange([towrole,onerole,group])" v-model="towrole.check">{{ towrole.name }}</el-checkbox>
                      </li>
                    </ul>
                  </template>
                </div>
              </template>
              <template v-else>
                <!--一级-->
                <ul>
                  <li v-for="onerole in group.permissions" :key="onerole.id">
                    <el-checkbox @change="handleItemChange([onerole,group])" v-model="onerole.check">{{ onerole.name }}</el-checkbox>
                  </li>
                </ul>
              </template>

            </div>
          </el-col>
        </el-form-item>
      </div>
    </el-form>
    <div class="save">
      <el-button @click="router.push('/setting/system/role')">取消</el-button>
      <el-button type="primary" @click="handleSave(ruleFormRef)">确定</el-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue'
import { RoleDetails, SaveRole } from '@/service/role'
import type { ElForm } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
interface IForm {
  id: number
  name: string //名称
  remark: string //备注
  privileges: Array
}
interface IRolePrivilege {
  id: number
  roleId: number
  route: Number
  privilege: Number
}
const form = ref<IForm>({
  id: useRoute().query.id ? Number(useRoute().query.id) : 0,
  name: '',
  remark: '',
  privileges: []
})
let privilege = Array([]) //选中的权限
const list = ref<Array>([]) //全部导航列表
const rules = reactive<IRules>({
  name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
})
type FormInstance = InstanceType<typeof ElForm>
const ruleFormRef = ref<FormInstance>()

const loadData = (): void => {
  RoleDetails({ id: form.value.id }).then((res: any) => {
    if (res.success) {
      list.value = res.data.privileges
      if (res.data.role) {
        form.value = res.data.role
        list.value.forEach((item: any) => {
          setGroupCheck(item)
          setGroupIndeterminate(item)
        })
      }
    }
  })
}
const setGroupCheck = (group: any): void => {
  if (group.permissions) {
    group.permissions.forEach((permission: any) => {
      console.log(permission)
      permission.check =
        form.value.privileges.filter((p) => p.privilege === permission.id && p.route === group.route).length > 0
    })
  } else {
    group.children.forEach((item: any) => {
      setGroupCheck(item)
    })
  }
}
const setGroupIndeterminate = (group: any): void => {
  if (group.children) {
    group.children.forEach((item: any) => {
      setGroupIndeterminate(item)
    })
  }
  updateCheck(group)
}

//下级跟随父级
const handleParentChange = (group: any): void => {
  group.isIndeterminate = false
  if (group.permissions) {
    group.permissions.forEach((permission: any) => {
      permission.check = group.check
    })
  } else if (group.children) {
    group.children.forEach((item: any) => {
      item.check = group.check
      handleParentChange(item)
    })
  }
}
//存在上级选择时候
const handleItemChange = (groups: Array): void => {
  groups.forEach((group: any, index: number) => {
    if (index === 0) handleParentChange(group)
    else updateCheck(group)
  })
}
//修改是否选中和半选
const updateCheck = (group: any): void => {
  group.isIndeterminate = false
  group.check = false
  let checklength = 0
  let length = 0
  if (group.permissions) {
    checklength = group.permissions.filter((p) => p.check).length
    length = group.permissions.length
  } else {
    checklength = group.children.filter((p) => p.check).length
    length = group.children.length
  }
  if (checklength > 0) {
    if (checklength === length) group.check = true
    else group.isIndeterminate = true
  } else {
    if (group.children && group.children.filter((p) => p.isIndeterminate).length > 0) {
      group.isIndeterminate = true
    }
  }
}
const handleSave = (formEl: FormInstance | undefined): void => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      privilege = []
      list.value.forEach((group: any) => {
        getRolePrivilege(group)
      })
      if (privilege.length === 0) return ElMessage.error('请选择角色权限')
      form.value.privileges = privilege
      SaveRole(form.value).then((res: any) => {
        if (res.success) {
          ElMessage.success('操作成功')
          router.push('/setting/system/role')
        } else ElMessage.error(res.msg)
      })
    }
  })
}
const getRolePrivilege = (group: any): void => {
  if (group.permissions) {
    group.permissions.forEach((item: any) => {
      if (item.check) {
        const rolePrivilege = reactive<IRolePrivilege>({
          id: 0,
          roleId: form.value.id,
          route: group.route,
          privilege: item.id
        })

        privilege.push(rolePrivilege)
      }
    })
  } else {
    group.children.forEach((item: any) => {
      getRolePrivilege(item)
    })
  }
}

onMounted(() => {
  loadData()
})
</script>
<style lang="scss" scoped>
@import '@/assets/styles/mixin.scss';
@import '@/assets/styles/formPage.scss';

$bg-color: #f7f8f9;

.add-role {
  padding-bottom: 24px;
}
.right-title {
  display: flex;
  height: 52px;
  align-items: center;
  padding-left: 16px;
  padding-right: 16px;
  background-color: rgba(0, 0, 0, 0.03);
  color: rgba(0, 0, 0, 0.85);
}
.role-right {
  ul {
    display: flex;
    margin: 8px 0 16px;
    padding: 0 40px;
    flex-wrap: wrap;
  }

  li {
    padding: 7px 24px 7px 0;
  }
}
.save {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px;
  padding-left: 185px;
  display: flex;
  justify-content: center;
  background-color: #fff;
  z-index: 1;
}
::v-deep {
  .el-checkbox {
    color: rgba(0, 0, 0, 0.65);
  }

  .is-checked .el-checkbox__label {
    color: rgba(0, 0, 0, 0.65);
  }
}
.ml40 {
  margin-left: 40px;
}
</style>
